package com.p7.framework.common.validator;

import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.p7.framework.common.ResultBean;
import com.p7.framework.controller.PersonController;

public class ValidatorUtils {

	private static final Logger logger = LoggerFactory.getLogger(PersonController.class);

	public static ResultBean beanValid(BindingResult bindingResult, LocaleService localeService) {

		if (bindingResult.hasErrors()) {

			Locale locale = LocaleContextHolder.getLocale();
			StringBuilder joinMessage = new StringBuilder();
			List<ObjectError> allErrors = bindingResult.getAllErrors();
			for (ObjectError objectError : allErrors) {
				joinMessage.append(",").append(localeService.getMessage(locale, objectError.getDefaultMessage()));
			}

			if (joinMessage.length() > 0) {
				String message = joinMessage.deleteCharAt(0).toString();
				logger.info("error message:" + message);
				return new ResultBean(ResultBean.SUCCESS, message);
			}

		}

		return null;

	}

}
